#!/bin/sh
#
#
#  ----------------------------------------------------------------------------
#  "THE BEER-WARE LICENSE" (Revision 42):
#  <intsig@gmail.com> wrote this file. As long as you retain this notice you
#  can do whatever you want with this stuff. If we meet some day, and you think
#  this stuff is worth it, you can buy me a beer in return KAB
#  ----------------------------------------------------------------------------
#
# Batch video converter, i guess #25883
#
# What it does:
#
# 	1. Takes a list of video files and converts them to xvid
#	2. Cropping: removes black borders 
#	3. Scaling to 640x360 (16:9 aka 1,78:1) or 640:272 (2,35:1)
#	4. normalizes Audio to CBR 192kBit
#
#	Note: 	- Just regular filenames, no Umlauts, spaces
#		- No commandline parsing, know what you do
#		- It fits MY NEEDS: No questions, no support, no discussion 
#
# What it NOT does:
#
#	1. A clean approach to coding
#	2. Fulfill all your transcoding needs
#	3. Being smart
#	4. Fancy GUI
# 
# What you need:
#	
#	1. mplayer with mencoder and the appropriate codecs
#	2. Bourne shell
#	3. Tested on OpenBSD & Mac OSX with homebrew
#	3. Anyone else: Good luck
#			

AUDIOPARAMS="-oac mp3lame -lameopts cbr:br=192 -srate 44100 -af lavcresample=44100,volnorm=1"
VBITRATE="1200"

for video in $@; do
	name=${video%\.*}
	CROPVAL=`mplayer ${video} -vf cropdetect -ss 180 -frames 3 -ao null \
	| awk -F 'crop=' '/crop/ {print $2}' | sed 's/)\.//g' | tr -d ' '`
	# Constructing filter parmams in dependency to cropping, if the last value ist gt 30 it's usually 2,35:1 ratio, else 1,78:1
	CROPPING=`echo ${CROPVAL} | cut -d: -f4-`
	
	if [ ${CROPPING} -gt 30 ]
	then
		SCALE="640:272"
	else
		SCALE="640:360"
	fi
	FILTER="harddup,crop=${CROPVAL},scale=${SCALE}" 
	VIDEOFILTER=`echo ${FILTER} | tr -d ' '`
	VIDEOPASS1="-ffourcc DX50 -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=${VBITRATE}:vhq:keyint=15:vpass=1:turbo -vf ${VIDEOFILTER}"
	VIDEOPASS2="-ffourcc DX50 -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=${VBITRATE}:vhq:keyint=15:vpass=2 -vf ${VIDEOFILTER}"
	mencoder $video -o $video.avi ${AUDIOPARAMS} ${VIDEOPASS1}
	mencoder $video -o $video.avi ${AUDIOPARAMS} ${VIDEOPASS2}


done



